package com.example.studykt.util;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.util.Log;

import com.example.studykt.entity.Databus;
import com.example.studykt.entity.PhoneDtoBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class PhoneAndSmsUtil {
    // 号码
    public final static String NUM = ContactsContract.CommonDataKinds.Phone.NUMBER;
    // 联系人姓名
    public final static String NAME = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME;

    //上下文对象
    private Context context;
    //联系人提供者的uri
    private Uri phoneUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;


    public Uri SMS_INBOX = Uri.parse("content://sms/");
    private SimpleDateFormat dateFormat = new SimpleDateFormat(
            "yyyy-MM-dd hh:mm:ss");
    private ArrayList<Databus> databuses=new ArrayList<>();


    public PhoneAndSmsUtil(Context context){
        this.context = context;
    }

    /**
     * 获取所有联系人
     */
    public List<PhoneDtoBus> Phone(){
        List<PhoneDtoBus> PhoneDtoBuss = new ArrayList<>();
        ContentResolver cr = context.getContentResolver();
        Cursor cursor = cr.query(phoneUri,new String[]{NUM,NAME},null,null,null);
        if (null == cursor) {
            Log.i("ooc", "获取所有联系人 == null");
            return null;
        }
        while (cursor.moveToNext()){
            PhoneDtoBus PhoneDtoBus = new PhoneDtoBus(cursor.getString(cursor.getColumnIndex(NAME)),cursor.getString(cursor.getColumnIndex(NUM)));
            PhoneDtoBuss.add(PhoneDtoBus);
        }
        return PhoneDtoBuss;
    }


    /**
     * 获取手机短信
     */
    public ArrayList<Databus> obtainPhoneMessage() {
        ContentResolver cr = context.getContentResolver();
        String[] projection = new String[]{"_id", "address", "person", "body", "date", "type"};
        Cursor cur = cr.query(SMS_INBOX, projection, null, null, "date desc");
        if (null == cur) {
            Log.i("ooc", "获取手机短信 == null");
            return null;
        }
        while (cur.moveToNext()) {
            Databus databus=new Databus() ;
            databus.set_id(cur.getString(cur.getColumnIndex("_id")));//id
            databus.setAddress(cur.getString(cur.getColumnIndex("address")));//发件人地址  即手机号
            databus.setPerson(cur.getString(cur.getColumnIndex("person")));//发件人
            databus.setDate(dateFormat.format(new Date(Long.parseLong(cur.getString(cur.getColumnIndex("date"))))));//日期
            databus.setType(cur.getString(cur.getColumnIndex("type")));//短信类型1是接收到的，2是已发出
            databus.setBody(cur.getString(cur.getColumnIndex("body")));//短信具体内容
            databuses.add(databus);

        }
        return databuses;
    }


}
